/**
 * CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

package com.cmcc.zysoft.infocollection.util;

import java.io.File;
import java.net.URLEncoder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpStatus;

/**
 * @author 袁凤建
 * <br />邮箱: yuan.fengjian@ustcinfo.com
 * <br />描述: ImageUploadUtil.java HttpClient实现远程图片上传.
 * <br />版本: 1.0.0
 * <br />日期: 2013-11-1 下午3:29:20
 * <br />CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

public class ImageUploadUtil {

	public static void main(String[] args) throws Exception {
		File file = new File("C:\\test.jpg");
		FilePart filePart = new FilePart("pic", file);
        Part[] parts = 
        	{ filePart, 
			  new StringPart("user_id", "1"),
			  new StringPart("shop_id", "212102365990"),
			  new StringPart("tilte", URLEncoder.encode("测试", "UTF-8")),
			  new StringPart("img_intro", "test_test"),
			  new StringPart("type", "0"),
			  new StringPart("source", "1"),
			  new StringPart("pic", "1")
        	};
		String data = postFile("http://221.179.176.29:8680/chelsea/image/upload_image", parts);
		System.out.println("====================================================");
		System.out.println(data);
		System.out.println("====================================================");
	}
	
	public static String postFile(String url, Part[] parts) {
		String result = "";
		PostMethod postMethod = new PostMethod(url);
		MultipartRequestEntity entity = new MultipartRequestEntity(parts, postMethod.getParams()); 
		postMethod.setRequestEntity(entity);
		HttpClient client = new HttpClient();
		//设置连接时间
		client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);
		try {
			int status = client.executeMethod(postMethod);
			if(status == HttpStatus.SC_OK) {
	            result = postMethod.getResponseBodyAsString();
	        } else {
	        	System.err.println("Method failed: " + postMethod.getStatusLine());
	        }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//释放连接
            postMethod.releaseConnection();
		}
        return result;
    }
}